﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using Coevery.Win.DetailViewModule;
using Coevery.AppFramework.WinForms.Messages;
using Coevery.AppFramework;
using Coevery.AppFramework.Metadata;
using Coevery.AppFramework.WinForms.MVC;
using Coevery.AppFramework.WinForms.Views;
using Coevery.AppFramework.Security;

namespace Coevery.Win.DocumentModule.Document
{
    public class DocumentDetailController : ObjectDetailController
    {
        private IDocumentDetailForm _documentView;
        private string _documentSubject = string.Empty;
        private string _parentObjectName = string.Empty;
        public override string ObjectName
        {
            get
            {
                return "Document";
            }
        }

        public override IActionResult Execute(ActionParameters parameters)
        {
            return DocumentAction(parameters);
        }

        public IActionResult DocumentAction(ActionParameters parameters)
        {
            string documentSubject = string.Empty;
            if(parameters.ContainsKey("DocumentSubject"))
                _documentSubject = parameters.Get<string>("DocumentSubject");
            if (parameters.ContainsKey("ParentObjectName"))
                _parentObjectName = parameters.Get<string>("ParentObjectName");
            if (parameters.ObjectName == "Document")
            {
                DocumentId = parameters.ObjectId;
            }
            else
            {
                ObjectType = parameters.ObjectName;
                this.ObjectId = parameters.ObjectId;
            }
            var detailView = ViewFactory.CreateView("DefaultDocumentDetailView") as IDocumentDetailForm;
            _detailView = detailView;
            _documentView = detailView;
            if (parameters.ContainsKey("PutDocumentEnable"))
            {
                string putDocumentEnable = string.Empty;
                putDocumentEnable = parameters.Get<string>("PutDocumentEnable");
                if (putDocumentEnable.Equals("false"))
                {
                    _documentView.SetDescriptionVisible(false);
                }
            }
            OnViewSet();
            return new ModalViewResult(detailView);
        }


        public Guid DocumentId { get; set; }

        public string ObjectType { get; set; }

        public override EntityDetailWorkingMode WorkingMode { get; set; }

        protected override object GetEntity()
        {
            var entity = (Coevery.Domain.Impl.Document)_objectSpace.GetOrNew(ObjectName, DocumentId, null);
            if (DocumentId != Guid.Empty)
            {
                ObjectType = entity.ObjectType;
                ObjectId = entity.ObjectId ?? Guid.Empty;
            }
            else
            {
                entity.Subject = _documentSubject;
            }
            return entity;
        }

        protected override void RefreshEntityId(object entity)
        {
            if (WorkingMode == EntityDetailWorkingMode.Add)
                DocumentId = _objectSpace.GetObjectId(ObjectName, entity);
        }

        protected override void OnViewSet()
        {
            base.OnViewSet();
            _documentView.Saved += ViewSaved;
            Type parentType = _objectSpace.ResolveType(ObjectType);
            if (parentType.GetProperty("Description") == null)
            {
                _documentView.SetDescriptionVisible(false);
            }
            if (parentType.GetProperty("LatestFeedbackOn") == null)
            {
                _documentView.SetModifyEditVisible(false);
            }
        }

        void ViewSaved(object sender, EventArgs e)
        {
            if(!OnSave()) return;
            ObjectSetChangedMessage message = new ObjectSetChangedMessage();
            message.ObjectName = ObjectType;
            if (!string.IsNullOrEmpty(_parentObjectName))
            {
                message.ParentObjectName = _parentObjectName;
            }
            EventAggregationManager.SendMessage(message);
        }

        protected override bool OnSaving()
        {
            
            SetProperValue(ObjectId, ObjectEntity, "ObjectId");
            SetProperValue(ObjectType, ObjectEntity, "ObjectType");

            var parentEntity = _objectSpace.GetOrNew(ObjectType, ObjectId, null);
            SetProperValue(AuthorizationManager.CurrentUserId, parentEntity, "ModifiedById");
            SetProperValue(DateTime.Now, parentEntity, "ModifiedOn");
            if (_documentView.AppandDescription)
            {
                var descriptionPro = parentEntity.GetType().GetProperty("Description");
                var document = (Coevery.Domain.Impl.Document)ObjectEntity;
                if (descriptionPro != null)
                {
                    object description = descriptionPro.GetValue(parentEntity,null);
                    string appandedDescription = description != null
                                                    ? description.ToString() + Environment.NewLine + document.DocumentText
                                                    : document.DocumentText;
                    descriptionPro.SetValue(parentEntity, appandedDescription,null);
                    _objectSpace.UpdateObject(parentEntity);
                }
            }
            if (_documentView.UpdateLatestFeadback)
            {
                var latestFeedbackOnPro = parentEntity.GetType().GetProperty("LatestFeedbackOn");
                if (latestFeedbackOnPro != null)
                {
                    latestFeedbackOnPro.SetValue(parentEntity, DateTime.Now,null);
                    _objectSpace.UpdateObject(parentEntity);
                }
            }

            //SetProperValue(DateTime.Now, ObjectEntity, "BinaryData"); //NEW binarydata for document

            return base.OnSaving(); 
        }

        protected override void OnSaved()
        {
            EventAggregationManager.SendMessage(new ObjectSetChangedMessage { ObjectName = ObjectName });
            _documentView.CloseView();
        }
    }
}
